package com.waymap.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.reflections.util.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.waymap.Thread.WmsThread;
import com.waymap.common.Constant;
import com.waymap.common.vo.ItemInventoryInfoVo;
import com.waymap.domain.User;
import com.waymap.service.ItemInventoryService;
import com.waymap.service.TransactionInventoryDetailsService;
import com.waymap.service.TransactionsService;
import com.waymap.service.UserService;
import com.waymap.utils.AuthonTokenUtil;
import com.waymap.utils.CommonEnum;
import com.waymap.utils.mq.MsgProducer;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**
 * @author vincent mai
 * 交易管理
 */

@Api(value = "WMS系统", tags = {"WMS-单据管理"})
@CrossOrigin
@RestController
@RequestMapping("/bintransfer")
public class BinTransferController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private TransactionsService transactionsService;
    @Autowired
    private TransactionInventoryDetailsService transactionInventoryDetailsService;
    @Autowired
    private ItemInventoryService itemInventoryService;
    @Autowired
    private MsgProducer producer;
    @Autowired
    private UserService userService;

    /*
    * 无任务上架出库库位，所有库位
    * */
    @ApiOperation(value = "移库-查询库位列表")
    @RequestMapping(value = "/getBinNameList", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Map> getBinNameList(@ApiParam(value = "商品条码或者SKU码") @RequestParam(required = false) String upc,
                                              @ApiParam(value = "当前用户token") @RequestParam(required = false) String token,
                                              @ApiParam(value = "用户Id") @RequestParam(required = false) String userId) {
        //无任务单号出库库位
        Map<String, Object> authonMap = AuthonTokenUtil.checkToken(token, userId);
        System.out.println(authonMap);
        User currentUser = null;
        String accountId = null;
        if ((authonMap != null) && ((Constant.NO).equals(authonMap.get("isAvailable")))) {
            return ResponseEntity.ok(authonMap);
        } else {
            currentUser = userService.getUserInfoByToken(token);
            if (currentUser == null) {
                authonMap.put("isAvailable", Constant.NO);
                authonMap.put("errorCode", Constant.TOKEN_ERRCODE_EXPIRE);
                authonMap.put("msg", "签名过期");
                return ResponseEntity.ok(authonMap);
            }
            accountId = currentUser.getAccountId();
        }
        Map<String, Object> param = new HashMap(16);
        param.put("accountId", accountId);
        /*param.put("upc", upc);
        param.put("itemName", upc);*/
        param.put("locationId",currentUser.getLocationId());
        List<Map<String, Object>> list = itemInventoryService.getLocationBinsList(param);
        Map<String, Object> map = new HashMap(16);
        if (null != list && list.size() > 0) {
            map.put("result", list);
            map.put("status", CommonEnum.value("eSuccess"));
            map.put("msg", CommonEnum.value("eSMessage"));
            return ResponseEntity.ok(map);
        }
        map.put("status", CommonEnum.value("eNotFind"));
        map.put("msg", CommonEnum.value("notFind"));
        return ResponseEntity.ok(map);
    }

    /*
    * 无任务上架入库库位，数量大于0
    * */
    @ApiOperation(value = "移库-查询商品信息")
    @RequestMapping(value = "/getItemInfoList", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Map> getItemInfoList(@ApiParam(value = "商品条码或者SKU码") @RequestParam(required = false) String upc,
                                               @ApiParam(value = "库位") @RequestParam(required = false) String binName,
                                               @ApiParam(value = "当前用户token") @RequestParam(required = false) String token,
                                               @ApiParam(value = "用户Id") @RequestParam(required = false) String userId
    ) {
        Map<String,Object> authonMap= AuthonTokenUtil.checkToken(token,userId);
        User currentUser = null;
        String accountId = null;
        if((authonMap !=null)&&((Constant.NO).equals(authonMap.get("isAvailable")))){
            return ResponseEntity.ok(authonMap);
        }else {
            currentUser = userService.getUserInfoByToken(token);
            if (currentUser == null) {
                authonMap.put("isAvailable", Constant.NO);
                authonMap.put("errorCode", Constant.TOKEN_ERRCODE_EXPIRE);
                authonMap.put("msg", "签名过期");
                return ResponseEntity.ok(authonMap);
            }
            accountId = currentUser.getAccountId();
        }
        Map<String, Object> param = new HashMap(16);
        param.put("upc", upc);
        param.put("itemName", upc);
        param.put("accountId",accountId);
        param.put("locationId",currentUser.getLocationId());
        if(binName!=null && binName.length()!=0){
            param.put("binName",binName);
        }
        List<Map<String, Object>> list = itemInventoryService.getItemInfoList(param);
        Map<String, Object> map = new HashMap(16);
        if (null != list && list.size() > 0) {
            map.put("result", list);
            map.put("status", CommonEnum.value("eSuccess"));
            map.put("msg", CommonEnum.value("eSMessage"));
        } else {
            map.put("status", CommonEnum.value("eNotFind"));
            map.put("msg", CommonEnum.value("notFind"));
        }
        return ResponseEntity.ok(map);
    }

    @ApiOperation(value = "提交移库行")
    @RequestMapping(value = "/saveTransactionLine", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Map> saveTransactionLine(@ApiParam(value = "请求体") @RequestBody(required = false) Map request) {
       /**参数示例:{token=759683b14dc545398fac823f5dacc8b0, upc=12345, itemId=76, binId=6, toBinId=34, quantity=1, transactionId=}**/
        Map<String,Object> authonMap=AuthonTokenUtil.checkToken(request.get("token").toString(),request.get("userId").toString());
        if((authonMap !=null)&&((Constant.NO).equals(authonMap.get("isAvailable")))){
            return ResponseEntity.ok(authonMap);
        }
        String tranId = transactionInventoryDetailsService.saveBinTransferDetailLine(request);
        Map tmp = new HashMap();
        tmp.put("tranId", tranId);
        Map<String, Object> map = new HashMap(16);
        map.put("result", tmp);
        map.put("status", CommonEnum.value("eSuccess"));
        map.put("msg", CommonEnum.value("eSMessage"));
        return ResponseEntity.ok(map);
    }

    @ApiOperation(value = "提交审核移库")
    @RequestMapping(value = "/submitTransaction", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Map> submitTransaction(@ApiParam(value = "请求体") @RequestBody(required = false) Map request) {
        /**参数示例{token=759683b14dc545398fac823f5dacc8b0, transactionId=BIN_TRANSFER2018_08_13_10_40_28}**/

    	String token = request.get("token").toString();
        Map<String,Object> authonMap=AuthonTokenUtil.checkToken(token,request.get("userId").toString());
        User currentUser;
        if ((authonMap != null) && ((Constant.NO).equals(authonMap.get("isAvailable")))) {
			return ResponseEntity.ok(authonMap);
		} else {
			currentUser = userService.getUserInfoByToken(token);
			if (currentUser == null) {
				authonMap.put("isAvailable", Constant.NO);
				authonMap.put("errorCode", Constant.TOKEN_ERRCODE_EXPIRE);
				authonMap.put("msg", "签名过期");
				return ResponseEntity.ok(authonMap);
			}else {
                request.put("accountId", currentUser.getAccountId());
                request.put("location", currentUser.getLocationId());
            }
		}
        return transactionsService.submitNoIRTNumber(request);
        /*Map<String, Object> map = new HashMap(16);
        if(null!=request.get("transactionId")){
            *//*****利用线程发送ACTIVE_MQ模块*****//*
            WmsThread wms = new WmsThread("wms-mq",(String)request.get("transactionId"),"BIN_TRANSFER",producer,"BIN_TRANSFER",currentUser.getAccountId());
            wms.start();
            map.put("status", CommonEnum.value("eSuccess"));
            map.put("msg", CommonEnum.value("eSMessage"));
        }else{
            map.put("status", CommonEnum.value("eNotFind"));
            map.put("msg", "获取transactionId为空,MQ推送失败");
        }
        return ResponseEntity.ok(map);*/
    }


    @ApiOperation(value = "根据当前用户查询库位列表")
    @RequestMapping(value = "/getInventoryPositionList", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Map> getInventoryPositionList(@ApiParam(value = "商品id") @RequestParam(required=false) String itemId,
                                                        @ApiParam(value = "当前用户token") @RequestParam String token,
                                                        @ApiParam(value = "用户Id") @RequestParam String userId) {

        Map<String, Object> authonMap = AuthonTokenUtil.checkToken(token, userId);
        System.out.println(authonMap);
        User currentUser = null;
        String accountId = null;
        if ((authonMap != null) && ((Constant.NO).equals(authonMap.get("isAvailable")))) {
            return ResponseEntity.ok(authonMap);
        } else {
            currentUser = userService.getUserInfoByToken(token);
            if (currentUser == null) {
                authonMap.put("isAvailable", Constant.NO);
                authonMap.put("errorCode", Constant.TOKEN_ERRCODE_EXPIRE);
                authonMap.put("msg", "签名过期");
                return ResponseEntity.ok(authonMap);
            }
            accountId = currentUser.getAccountId();
        }
        Map<String, Object> param = new HashMap(16);
        List<Map<String, Object>> list=null;
        if (Utils.isEmpty(itemId)) {
            param.put("locationId", currentUser.getLocationId());
            param.put("accountId", accountId);
            list = itemInventoryService.getLocationBinsList(param);
        }else{
            if("4857309".equals(accountId) || "4857309_SB2".equals(accountId)){
                param.put("accountId", accountId);
                param.put("itemId", itemId);
                param.put("locationId",currentUser.getLocationId());
                list = itemInventoryService.selectByItemId(param);
            }
        }
        Map<String, Object> map = new HashMap(16);
        if (null != list && list.size() > 0) {
            map.put("result", list);
            map.put("status", CommonEnum.value("eSuccess"));
            map.put("msg", CommonEnum.value("eSMessage"));
            return ResponseEntity.ok(map);
        }
        map.put("status", CommonEnum.value("eNotFind"));
        map.put("msg", CommonEnum.value("notFind"));
        return ResponseEntity.ok(map);
    }
}
